package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"time"
)

type Book struct {
	Id          uint `gorm:"primary_key"`
	Title       string
	Price       uint
	IsPublished byte `gorm:"default:1"`
	PublishDate *time.Time
	CreatedDate *time.Time `gorm:"autoCreateTime"`
	UpdatedDate *time.Time `gorm:"autoCreateTime"`
}

type User struct {
	gorm.Model
	Name string
}

//type Model struct {
//	Id          uint      `gorm:"primary_key"`
//	CreatedDate time.Time `gorm:"autoCreateTime"`
//	UpdatedDate time.Time `gorm:"autoCreateTime"`
//	DeletedDate time.Time `gorm:"index"`
//}

func main() {
	db, err := gorm.Open("mysql", "root:123456@(127.0.0.1:3306)/gin?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
	}
	defer db.Close()

	//自动迁移
	//db.AutoMigrate(&Book{})

	//插入单条数据
	//book := Book{Title: "西游记", Price: 19}
	//db.Create(&book)

	//插入多条数据
	//now := time.Now()
	//book := []Book{
	//	{Title: "唐诗三百首", Price: 58},
	//	{Title: "资本论", Price: 36},
	//	{Title: "资治通鉴", Price: 27},
	//}

	//if err := db.Create(&book).Error; err != nil {
	//	fmt.Println(err)
	//}
	//db.Create(&book[0])
	//db.Create(&book[1])
	//db.Create(&book[2])

	//查询所以记录
	//allBook := []Book{}
	//ret := db.Find(&allBook)
	//fmt.Println(ret.RowsAffected)
	//for i := range allBook {
	//	fmt.Println(i, allBook[i])
	//}

	//查询单条记录
	//f := Book{}
	//db.First(&f)
	//fmt.Println(f)
	//l := Book{}
	//db.Last(&l)
	//fmt.Println(l)

	//String条件
	//a := Book{}
	//db.Where("title=?", "红楼梦").First(&a)
	//fmt.Println(a)
	//b := Book{}
	//db.Where("price=?", 29).Find(&b)
	//fmt.Println(b)
	//c := Book{}
	//db.Where("price between ? and ?", 29, 99).Find(&c)
	//fmt.Println(c)
	//d := Book{}
	//db.Where("price in ?", []int16{19, 29, 99}).Find(&d)
	//fmt.Println(d)
	//e := []Book{}
	//db.Where("title like ?", "水%").Find(&e)
	//fmt.Println(e)
	//f := []Book{}
	//db.Where(map[string]interface{}{"title": "水浒传", "price": 29}).Find(&f)
	//fmt.Println(f)

	//select,omit语句，查询字段
	//g := []Book{}
	//db.Select("title,price").Find(&g)
	//排除
	//db.Omit("isPublished", "publishDate", "createdDate", "updatedDate")
	//fmt.Println(len(g), g)

	//删除一条
	//book := Book{Id: 1}
	//db.Debug().Delete(&book)

	//按条件删除
	//db.Debug().Where("price between 29 and 99").Delete(Book{})
	//db.Where("1==1").Delete(&Book{})

	//更新
	//b := Book{}
	//db.First(&b)
	//b.Title = "西游记"
	//db.Save(&b)
	//b := Book{Id: 10}
	//db.Debug().Model(&b).Update("title", "人间词话")
	//db.Debug().Model(&Book{}).Where("id=?", 10).Update("title", "赤壁赋")
	//db.Debug().Model(&Book{}).Where("id=?", 10).Update(map[string]interface{}{"isPublished": false})
}
